<?php
/**
 * User: Jerry
 * Date: 2017/11/10
 * Time: 14:46
 */

namespace SDXApi\Service;


use SDXApi\Abstracts\TemplateAbstract;
use SDXApi\Model\HomeTemplateGoodsNewModel;
use SDXApi\Repositories\GoodsRepository;
use Think\Page;

/**
 * Class HomeTemplateGoodsNewService
 * @author Jerry
 * @package SDXApi\Service
 */
class HomeTemplateGoodsNewService extends TemplateAbstract
{
    /**
     * @var HomeTemplateGoodsNewModel
     */
    protected $goodsNewModel;

    /**
     * @var GoodsRepository
     */
    protected $goodsRepository;


    /**
     * HomeTemplateGoodsNewService constructor.
     */
    public function __construct()
    {
        $this->goodsNewModel = new HomeTemplateGoodsNewModel();
        $this->goodsRepository = new GoodsRepository();
    }

    /**
     * @author Jerry
     * @param array $template
     * @param int $userId
     * @param int $wid
     * @return array
     */
    public function handle($template = array(), $userId = 0, $wid = 8)
    {

        $cacheName = 'home_template_goods_new_id_' . $template['id'] . '_wid_' . $wid;

//        $goods = $this->getCache($cacheName);

        if (empty($goods)) {
            $data = $this->getGoodsNew($wid, 6);

            $this->goodsRepository->userId = $userId;
            $this->goodsRepository->wid = $wid;
            $goods = $this->goodsRepository->formatGoodsTransform($data);

            if (! empty($goods)) {
                $this->cacheData($goods, mt_rand(3600, 4200));
            }
        }

        if (empty($goods)) {
            $goods = array();
        }

        $template['goods_list'] = $goods;

        return $template;
    }


    /**
     * @author Jerry
     * @param int $userId
     * @param int $wid
     * @param int $limit
     * @param int $pageNumber
     * @return array|bool
     */
    public function getGoodsNewByLimit($userId = 0, $wid = 8, $limit = 100, $pageNumber = 1)
    {
        $pageArr = show_page($limit, $pageNumber);
        $isLast = 0;
        if ($pageNumber >= $pageArr['pagecount']) {
            $isLast = 1;
        }
        $data = $this->getGoodsNew($wid, $limit, $pageNumber);

        $this->goodsRepository->userId = $userId;
        $this->goodsRepository->wid = $wid;
        $goods = $this->goodsRepository->formatGoodsTransform($data);



        if (empty($goods)) {
            $goods = array();
        }

        $result = array(
            'data'          =>  $goods,
            'is_bottom'     =>  $isLast,
            'page'          =>  $pageArr
        );

        return $result;
    }

    /**
     * @author Jerry
     * @param int $wid
     * @param int $limit
     * @param int $pageNumber
     * @return mixed
     */
    protected function getGoodsNew($wid = 8, $limit = 100, $pageNumber = 1)
    {
        return $this->goodsNewModel->findGoodsNew($wid, $limit, $pageNumber);
    }
}